//配置文件
const config = require('./configs');
const Koa = require('koa');
const koaBody = require('koa-body');
const userAgent = require('koa-useragent').userAgent;

const jwt = require('koa-jwt');
const checkToken = require('./middlewares/checkToken');
const isNeedToken = require('./middlewares/isNeedToken');
const auth = require('./middlewares/auth');

const app = new Koa();
const router = require('./router');

app.use(
  koaBody({
    multipart: true,
    formidable: {
      maxFileSize: 60 * 1024 * 1024 // 设置上传文件大小最大限制，默认60M
    }
  })
);
process.on('unhandledRejection', (reason, p) => {
  console.log('Unhandled Rejection at:', p, 'reason:', reason);
});

// 错误处理
app.use((ctx, next) => {
  return next().catch((err) => {
    if (err.status === 401) {
      ctx.status = 401;
      ctx.body = 'Protected resource, use Authorization header to get access\n';
      return;
    } else {
      throw err;
    }
  });
});

app.use(userAgent);

app.use(
  jwt({
    secret: config.jwt.key
  }).unless({
    custom: isNeedToken
  })
);

//使用checkToken中间件
app.use(checkToken);

// //输出请求的方法，url,和所花费的时间
app.use(async (ctx, next) => {
  let start = new Date();
  await next();
  let ms = new Date() - start;
  console.log(
    new Date() + '：' + `${ctx.url}${JSON.stringify(ctx.query)} - ${ms} ms`
  );
});

//权限控制中间件
app.use(auth);
//使用路由中间件
app.use(router.routes()).use(router.allowedMethods());

//监听端口
app.listen(config.app.port, () => {
  console.log('The server is running at http://localhost:' + config.app.port);
});
